<?php

namespace App\Http\Controllers\Api;

use App\Models\{GradeLog, PointsLog, UserGrade, WebConfig};
use Illuminate\Support\Facades\DB;

class SignInController extends Controller
{
    /**
     * 此方法把签到做为登录
     * 更新 yf_user_base 表的 user_login_time 和 user_login_times 字段
     * 更新 ucenter_user_bind_connect 表的 bind_time
     * 更新 yf_user_info 表的 user_logintime 和 lastlogintime ?
     * 更新 ucenter_user_info_detail 表的 user_lastlogin_time 和 user_count_login ?
     */
    public function store()
    {
        if (PointsLog::isTodaySignIn(auth('api')->user()->user_id)) {
            return $this->failed('请勿重复签到！');
        }

        $dateTime = now()->toDateTimeString();

        $userBase = auth('api')->user()->userBase;
        $userBase->user_login_time = $dateTime;
        $userBase->user_login_times += 1;
        $userBase->save();

        auth('api')->user()->update(['bind_time' => $dateTime]);

        $yfUserInfo = auth('api')->user()->yfUserInfo;
        $yfUserInfo->update(['user_logintime' => $dateTime, 'lastlogintime' => $dateTime]);

        $userInfoDetail = auth('api')->user()->userInfo->userInfoDetail;
        $userInfoDetail->user_lastlogin_time = $dateTime;
        $userInfoDetail->user_count_login += 1;
        $userInfoDetail->save();

        $userResource = auth('api')->user()->userResource;
        DB::transaction(function () use ($dateTime, $yfUserInfo, $userResource) {
            // 为当前用户增加积分和成长值
            $points = (int)WebConfig::value("points_login");
            $grade = (int)WebConfig::value("grade_login");
            $userResource->user_points =+ $points;
            $userResource->user_growth =+ $grade;
            $userResource->save();

            // 积分变动记录
            PointsLog::insert([
                'user_id' => $yfUserInfo->user_id,
                'user_name' => $yfUserInfo->user_name,
                'class_id' => 2,
                'points_log_points' => $points,
                'points_log_time' => $dateTime,
                'points_log_desc' => '会员登录',
                'points_log_flag' => 'login',
            ]);
            // 成长值变动记录
            GradeLog::insert([
                'user_id' => $yfUserInfo->user_id,
                'user_name' => $yfUserInfo->user_name,
                'class_id' => 1,
                'grade_log_grade' => $grade,
                'grade_log_time' => $dateTime,
                'grade_log_desc' => '会员登录',
                'grade_log_flag' => 'login',
            ]);
        });

        // 尝试升级
        UserGrade::upgrade($userResource, $yfUserInfo);

        return $this->success($userResource->toArray());
    }
}
